package cn.itsource.config;

import cn.itsource.constants.RConst;
import cn.itsource.mapper.LoginMapper;
import cn.itsource.mapper.RoleMapper;
import cn.itsource.pojo.domain.Login;
import cn.itsource.pojo.domain.Role;
import cn.itsource.utils.IdUtil;
import cn.itsource.utils.NameUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 初始话admin用户账号
 */
@Component
public class BootstrapListener  implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RoleMapper roleMapper;

	@Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Login login = loginMapper.selectOne(new LambdaQueryWrapper<Login>()
                .eq(Login::getUsername, "admin")
                .eq(Login::getType, RConst.Num.BASE_LONG_0));
        if (login == null) {
            //加密
            String encode = passwordEncoder.encode("123456");
            System.err.println(encode);
            Login build = Login.builder()
                    .id(IdUtil.getId())
                    .username("admin")
                    .password(encode)
                    .type(RConst.Num.INT_0)
                    .createTime(new Date())
                    .avatar(null)
                    .name(NameUtil.getName())
                    .nickName(NameUtil.getAdminName())
                    .admin(RConst.Num.INT_1)
                    .build();
            //查询role角色信息
            Role roleId = roleMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getSn, "admin"));
            // 账号赋予角色
            loginMapper.insertAdminAndRole(build.getId(),roleId.getId(),IdUtil.getId());
            // 初始账号
            loginMapper.insert(build);
        }
    }
}